<?php

namespace App\Http\Controllers\UserCenter;

use App\Http\Controllers\Component\MasterResponseController;
use App\Http\Requests\Admin\GoodsRequest;
use App\Model\Creator;
use App\Model\Genre;
use App\Model\Goods;
use App\Model\GoodsPutaway;
use App\Model\Order;
use App\User;
use Illuminate\Http\Request;
use Auth;
use Webpatser\Uuid\Uuid;
use DB;
use Illuminate\Support\Facades\Storage;

class MyCraftsController extends MasterResponseController
{
    public function __construct()
    {
        $this->middleware('isCreator');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $genres = Genre::all();
        $creator = Creator::where('user_id', Auth::id())->first();
        $crafts = Goods::where('creator_id', $creator->id)
            ->where('status', '=', 1)
            ->get();
        $data = array(
            'genres' => $genres,
            'creator' => $creator,
            'crafts' => $crafts,
        );
        return view('user_center.myCrafts', compact('data'));
    }

    public function getCrafts($creator_id)
    {
        $crafts = Goods::where('creator_id', $creator_id)
            ->where('status', '=', 1)
            ->get();
        return parent::withData($crafts);
    }

    public function getSold($creator_id)
    {
        $craftsSold = Goods::where('creator_id', $creator_id)
            ->where('status', '=', 2)
            ->get();
        return parent::withData($craftsSold);
    }

    public function getDeleted($creator_id)
    {
        $deleted = Goods::onlyTrashed()->where('creator_id', $creator_id)->get();
        return parent::withData($deleted);
    }

    public function getPutAwayApply($creator_id)
    {
        $putAwayApply = GoodsPutaway::where('creator_id', $creator_id)
            ->where('status', true)
            ->get();
        return parent::withData($putAwayApply);
    }

    public function getBeRejected($creator_id)
    {
        $putAwayApplyOfBeRejected = GoodsPutaway::where('creator_id', $creator_id)
            ->where('status', false)
            ->get();
        return parent::withData($putAwayApplyOfBeRejected);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return null;
    }

    /**
     * * Store a newly created resource in storage.
     * @param GoodsRequest $request
     * @param GoodsPutaway $model
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */

    //添加作品上架申请
    public function store(GoodsRequest $request)
    {
        $upload = $request->file;
        $data = $request->all();
        if ($upload->isValid()) {
            $path = '/images/goods/' . $upload->store('', 'goods');
        }
        $id =Uuid::generate(4);
        GoodsPutaway::create([
            'id' => $id,
            'name' => $data['name'],
            'author' => $data['author'],
            'size' => $data['size'],
            'price' => $data['price'],
            'intro' => $data['intro'],
            'imgUrl' => $path,
            'genre_id' => $data['genre_id'],
            'creator_id' => $data['creator_id'],
            'status' => true,
        ]);
        $goods = DB::table('audit_putaways_v')->where('id',$id)->first();
        $message = '上架申请已提交，请等待管理员审核！';
        return parent::successWithData($message,$goods);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return null;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return null;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */

    //修改作品信息
    public function updateCraft(GoodsRequest $request)
    {
        Goods::where('id', $request['id'])->update([
            'name' => $request['name'],
            'author' => $request['author'],
            'intro' => $request['intro'],
            'price' => $request['price'],
            'size' => $request['size'],
            'genre_id' => $request['genre_id']
        ]);
        $goods = Goods::where('id', $request['id'])->first();
        return parent::successWithData('作品信息已修改', $goods);
    }

    //修改申请
    public function updatePutAwayApply(GoodsRequest $request)
    {
        GoodsPutaway::where('id', $request['id'])->update([
            'name' => $request['name'],
            'author' => $request['author'],
            'intro' => $request['intro'],
            'price' => $request['price'],
            'size' => $request['size'],
            'status' => 1,
            'genre_id' => $request['genre_id'],
        ]);
        return parent::success('申请信息已修改并重新提交审核!审核结果将通过邮箱通知您');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
//        GoodsPutaway::destroy($id);
//        return parent::success('申请已驳回');
    }

    //删除
    public function myDelete(Request $request)
    {
        $count=Order::where('goods_id',$request['id'])->where('status','<>',4)->where('status','<>',5)->count('*');
        if ($count>0){
            return parent::error('删除失败，该作品存在正在进行中订单！');
        }
        //判断是否为软删除
        if ($request['isSoftDel'] == '1') {
            Goods::where('id', $request['id'])->delete();
        } else {
            if ($request['table'] == 'goods') {
                //删除作品图片
                $imgPath = Goods::withTrashed()->where('id', $request['id'])->value('imgUrl');
                if ($imgPath != '') {
                    $imgPath = explode('/',$imgPath);
                    $imgPath = $imgPath[count($imgPath)-1];
                    $imgPath = str_replace('}', '', $imgPath);
                    $imgPath = str_replace('"', '', $imgPath);
                    Storage::disk('goods')->delete($imgPath);
                }
                //从数据库彻底删除
                Goods::where('id', $request['id'])->forceDelete();
            } elseif ($request['table'] == 'goods_putaways') {
                GoodsPutaway::destroy($request['id']);
            }
        }
        return parent::success('数据已删除！');
    }

    public function restore($id)
    {
        Goods::where('id', $id)->restore();
        return parent::success('数据已恢复！');
    }
}
